package top.jiangqiang.qyblog.core.storage;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.BooleanUtil;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import top.jiangqiang.qyblog.common.config.GlobalProperties;
import top.jiangqiang.qyblog.core.domain.entity.Storage;
import top.jiangqiang.qyblog.core.storage.impl.S3AsyncStorageClient;
import top.jiangqiang.qyblog.core.storage.impl.S3StorageClient;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
@RequiredArgsConstructor
public class S3Container {
    private final Map<Long, S3AsyncStorageClient> s3AsyncClientMap = new ConcurrentHashMap<>();
    private final Map<Long, S3StorageClient> s3ClientMap = new ConcurrentHashMap<>();
    private final GlobalProperties globalProperties;

    public synchronized StorageClient getStorageClient(Storage storage, Boolean isSync) {
        if (BooleanUtil.isTrue(isSync)) {
            return getS3Client(storage);
        } else {
            return getS3AsyncClient(storage);
        }
    }

    public synchronized S3AsyncStorageClient getS3AsyncClient(@NotNull Storage storage) {
        Long storageId = storage.getId();
        S3AsyncStorageClient s3AsyncStorageClient = s3AsyncClientMap.get(storageId);
        if (s3AsyncStorageClient != null) {
            if (s3AsyncStorageClient.test()) {
                return s3AsyncStorageClient;
            } else {
                IoUtil.close(s3AsyncStorageClient);
            }
        }
        s3AsyncStorageClient = new S3AsyncStorageClient(storage, globalProperties);
        s3AsyncClientMap.put(storageId, s3AsyncStorageClient);
        return s3AsyncStorageClient;
    }

    public synchronized S3StorageClient getS3Client(@NotNull Storage storage) {
        Long storageId = storage.getId();
        S3StorageClient s3StorageClient = s3ClientMap.get(storageId);
        if (s3StorageClient != null) {
            if (s3StorageClient.test()) {
                return s3StorageClient;
            } else {
                IoUtil.close(s3StorageClient);
            }
        }
        s3StorageClient = new S3StorageClient(storage, globalProperties);
        s3ClientMap.put(storageId, s3StorageClient);
        return s3StorageClient;
    }

}
